package com.gun3y.http;

import java.io.IOException;

import javax.annotation.PreDestroy;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import com.gun3y.exception.ExceptionCode;
import com.gun3y.exception.SWException;
import com.gun3y.utils.Commons;

@Service
public class HttpConnector {

    PoolingHttpClientConnectionManager cm;

    public HttpConnector() {
	cm = new PoolingHttpClientConnectionManager();
	// Increase max total connection to 200
	cm.setMaxTotal(200);
	// Increase default max connection per route to 20
	cm.setDefaultMaxPerRoute(20);
    }

    @PreDestroy
    public void release() {
	cm.close();
    }

    public String get(String url) {
	return get(url, Commons.DEFAULT_ENCODING);
    }

    public String get(String url, String encoding) {

	if (StringUtils.isBlank(url)) {
	    throw new SWException(ExceptionCode.InvalidInput);
	}

	if (!url.startsWith("http")) {
	    url = "http://" + url;
	}

	CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm).build();

	HttpGet httpGet = new HttpGet(url);
	CloseableHttpResponse response = null;
	try {
	    response = httpclient.execute(httpGet);

	    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
		throw new SWException(ExceptionCode.NoConnection);
	    }

	    return EntityUtils.toString(response.getEntity(), encoding);
	}
	catch (Exception e) {
	    throw new SWException(ExceptionCode.NoConnection);
	}
	finally {
	    if (response != null) {
		try {
		    response.close();
		}
		catch (IOException e) {
		}
	    }
	}
    }
}
